using GrapeCity.Forguncy.Commands;
using GrapeCity.Forguncy.Log;
using GrapeCity.Forguncy.Plugin;
using GrapeCity.Forguncy.ServerApi;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;

namespace TaskSyncOperation
{
    [Icon("pack://application:,,,/TaskSyncOperation;component/Resources/Icon_Info.png")]
    [Designer("TaskSyncOperation.Designer.TaskSyncOperationServerCommandDesigner, TaskSyncOperation")]
    [Category("异步调用")]
    public class WaitAll : Command, ICommandExecutableInServerSideAsync
    {
        [FormulaProperty]
        [DisplayName("任务标识列表")]
        [Description("【注册异步任务】的返回值或多个返回值组成的数组/列表。")]
        public object TargetProperty { get; set; }

        [FormulaProperty]
        [DisplayName("超时时间（毫秒）")]
        public object TimeoutProperty { get; set; } = 30 * 1000; // 默认30秒

        [ResultToProperty]
        [DisplayName("将执行结果保存到：")]
        [Description(" 返回执行完毕的任务数量，-1表示超时或没有任务完成")]
        public string ResultTo { get; set; } = "WaitAll执行结果";

        public async Task<ExecuteResult> ExecuteAsync(IServerCommandExecuteContext dataContext)
        {
            var targets = await dataContext.EvaluateFormulaAsync(this.TargetProperty);
            var timeout = await dataContext.EvaluateFormulaAsync(this.TimeoutProperty);


            int result= await TaskRunner.Instance.WaitAllTasks(ArrayHelper.GetArray(targets),int.Parse(timeout.ToString())); // 启动所有未开始的任务

            dataContext.Parameters[ResultTo] = result; // 将执行结果保存到指定的参数中

            return new ExecuteResult();
        }

        public override string ToString()
        {
            return "执行并等待全部任务完成";
        }

        public override CommandScope GetCommandScope()
        {
            return CommandScope.ExecutableInServer;
        }
    }
}
